package com.yyfax.infrastructure.upgrade;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import com.yyfax.infrastructure.Constants;
import com.yyfax.infrastructure.R;

import static com.yyfax.infrastructure.upgrade.Updater.RESULT_CODE_KILL;

/**
 * Created by HenryZhang on 2016/12/28.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class UpdateDialog {
	static void show(final Activity aty, final CheckVersionInfoTask.VersionInfo info) {
		if (!aty.isFinishing()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(aty);
			builder.setTitle(R.string.update_dialog_title);
			builder.setMessage(info.versionDesc)//Html.fromHtml(desc))
					.setPositiveButton(R.string.update_dialog_btn_download, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							Intent intent = new Intent(aty.getApplicationContext(), DownloadService.class);
							intent.putExtra(Constants.APK_DOWNLOAD_URL, info.apkUrl);
							intent.putExtra(Constants.APPLICATION_ID, info.applicationId);
							aty.startService(intent);

							dialog.dismiss();
							exit(aty, info.forceUpdate);
						}
					})
					.setNegativeButton(info.forceUpdate ? R.string.update_dialog_btn_cancel_force : R.string.update_dialog_btn_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.dismiss();
									exit(aty, info.forceUpdate);
								}
							}
					);

			AlertDialog dialog = builder.create();
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();
		}
	}

	private static void exit(Activity aty, boolean forceUpdate) {
		Updater.setDialogHadShowed(false);
		if (forceUpdate) {
			aty.setResult(RESULT_CODE_KILL);
			aty.finish();
		}
	}
}
